<script lang="ts" setup>
import {useRoute} from 'vue-router'
import {ref} from "vue"
import {getByIdAdminAttr, postAdminAttr, putAdminAttr} from "../serve"
import JsImages from "./js-images.vue"
import {ElMessage} from "element-plus"
import JsEditor from "./js-editor.vue"
import {FileToBase64} from "../utils.ts"

const
    route = useRoute(),
    fromData = ref({
      id: '',
      "name": "",
      "description": '',
      pic: '',
      address: ''
    }),
    loading = ref(false),
    isAdd = ref(false),
    fromRules = {
      name: [
        {
          required: true,
          min: 1,
          max: 100,
          message: '景点名长度1-100位',
          trigger: 'trigger',
        },
      ],
      description: [
        {
          required: true,
          min: 1,
          message: '请输入景点描述',
          trigger: 'trigger',
        },
      ],
      pic: [
        {
          required: true,
          trigger: 'trigger',
          message: '请上传封面图',
        },
      ],
      address: [
        {
          required: true,
          min: 1,
          max: 100,
          message: '请选择景点地址',
          trigger: 'trigger',
        },
      ],
    },
    froms = ref(),
    inImage = ref(false),
    positionVisible = ref(false)
;

function get() {
  if (route.query['id']) {
    loading.value = true
    isAdd.value = false
    getByIdAdminAttr(route.query['id']).then((r: any) => {
      fromData.value = r
      loading.value = false
      inImage.value = true
    }).catch(() => loading.value = false)
  } else {
    isAdd.value = true
  }
}

get()

function deleteChange() {
  fromData.value.pic = ' '
}

function loadFile(e: any) {
  loading.value = true
  FileToBase64(e).then((r: any) => {
    fromData.value.pic = r
    loading.value = false
  })
}

async function change() {
  try {
    await froms.value.validate()
    loading.value = true
    if (isAdd.value) {
      postAdminAttr({...fromData.value}).then(() => {
        loading.value = false
        ElMessage({type: 'success', message: '新增成功！'})
      }).catch(() => loading.value = false)
      return
    }
    putAdminAttr({...fromData.value}).then(() => {
      ElMessage({type: 'success', message: '修改成功！'})
      get()
    }).catch(() => loading.value = false)
  } catch (e) {
  }
}

function positionClose() {
  positionVisible.value = false
}

window.addEventListener('message', function (event) {
  // 接收位置信息，用户选择确认位置点后选点组件会触发该事件，回传用户的位置信息
  const data = event.data
  if (data && data.module === 'locationPicker') {//防止其他应用也会向该页面post信息，需判断module是否为'locationPicker'
    console.table(data)
    fromData.value = {
      ...fromData.value, ...{
        address: data['poiaddress'] + data['poiname'],
        latitude: data['latlng'].lat,
        longitude: data['latlng'].lng
      }
    }
    positionClose()
  }
  return false
}, false)
</script>

<template>
  <el-scrollbar>
    <el-card v-loading="loading" box element-loading-text="加载中...">
      <template #header>{{ isAdd ? '景点添加' : '景点编辑' }}</template>
      <el-form ref="froms" :model="fromData" :rules="fromRules" el-From>
        <el-form-item label="景点名称：" prop="name">
          <el-input :show-word-limit="true"
                    :maxlength="30" v-model="fromData['name']" :rows="4" placeholder="请输入景点名"
                    type="textarea"/>
        </el-form-item>
        <el-form-item label="景点地址：" prop="address">
          <el-input v-model="fromData['address']" @click="positionVisible = true" placeholder="请选择景点地址">
            <template #append>
              <el-button icon="Pointer" @click="positionVisible = true"/>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item label="景点图片：" prop="pic">
          <jsImages v-if="isAdd ? true : inImage" :picUrl="fromData.pic" @myPicFile="loadFile"
                    @delete-change="deleteChange"/>
        </el-form-item>
        <el-form-item label="景点描述：" prop="description">
          <js-editor v-model="fromData.description" :Value="fromData.description"
                     :default-config="{placeholder:'请输入景点描述...'}" :open="inImage" Height="400px"
                     style="width: 100%;"/>
        </el-form-item>
        <el-form-item>
          <el-button round style="width: 80%;margin: auto;" type="success" @click="change">立即提交</el-button>
        </el-form-item>
      </el-form>
    </el-card>
    <el-dialog v-model="positionVisible" :before-close="positionClose"
               style="user-select:none"
               title="选择位置" top="50px" width="60%">
      <iframe v-if="positionVisible" id="mapPage" frameborder=0 height="100%"
              src="https://apis.map.qq.com/tools/locpicker?search=1&type=1&key=3WDBZ-HMUCX-NIE43-ZPLQ4-OOHAO-OKBES&referer=myapp"
              style="width: 100%;height: 75vh;"
              width="100%"></iframe>
      <div slot="footer" class="dialog-footer">
        <el-button @click="positionClose">取消</el-button>
      </div>
    </el-dialog>
  </el-scrollbar>
</template>

<style lang="scss" scoped>
[box] {
  width: 80%;
  margin: auto;
}

[el-From] {
  width: 98%;
  margin: auto;
}
</style>